package com.wangsd.web.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wangsd.common.basicbean.Result;
import com.wangsd.common.component.WxpayService;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.utils.HttpClientUtils;
import com.wangsd.common.utils.MD5Utils;
import com.wangsd.web.api.service.OpenService;
import com.wangsd.web.mqpay.entity.Customer;
import com.wangsd.web.mqpay.entity.Merchant;
import com.wangsd.web.mqpay.entity.Passageway;
import com.wangsd.web.mqpay.service.CustomerService;
import com.wangsd.web.mqpay.service.MerchantService;
import com.wangsd.web.mqpay.service.PassagewayService;
import com.wangsd.web.mqpay.service.TradeService;
import com.wangsd.web.sys.entity.SysCompany;
import com.wangsd.web.sys.service.SysCompanyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Api(tags = "接口管理")
@RestController
@RequestMapping("/api/open")
@Slf4j
public class OpenController {
    @Value("${notify_url}")
    private String notify_url;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private OpenService openService;
    @Autowired
    private PassagewayService passagewayService;
    @Autowired
    private TradeService tradeService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    SysCompanyService companyService;

    @ApiOperation(value = "创建订单")
    @PostMapping("/createOrder")
    public Object createOrder(@ApiParam(value = "商户号(签名)", required = true) @RequestParam String customerNo,
                              @ApiParam(value = "商户订单号(签名)", required = true) @RequestParam String outTradeNo,
                              @ApiParam(value = "签名", required = true) @RequestParam String sign,
                              @ApiParam(value = "回调地址(签名)", required = true) @RequestParam String notifyUrl,
                              @ApiParam(value = "支付标识(签名)", required = true) @RequestParam String payCode,
                              @ApiParam(value = "金额(分)(签名)", required = true) @RequestParam String amount) {
        if (StringUtils.isBlank(customerNo)) {
            throw new BusinessException("商户号不能为空");
        }
        if (StringUtils.isBlank(outTradeNo)) {
            throw new BusinessException("商户订单号不能为空");
        }
        if (StringUtils.isBlank(sign)) {
            throw new BusinessException("签名不能为空");
        }
        if (StringUtils.isBlank(notifyUrl)) {
            throw new BusinessException("回调地址不能为空");
        }
        if (StringUtils.isBlank(payCode)) {
            throw new BusinessException("支付标识不能为空");
        }
//        if (StringUtils.isBlank(payType)) {
//            throw new BusinessException("支付方式不能为空");
//        }
        if (Integer.parseInt(amount) <= 0) {
            throw new BusinessException("金额不能为空");
        }

        //组装验签参数
        SortedMap<String, String> param = new TreeMap();
        param.put("customerNo", customerNo);
        param.put("outTradeNo", outTradeNo);
        param.put("notifyUrl", notifyUrl);
        param.put("payCode", payCode);
        param.put("amount", amount);
        Customer customer = customerService.selectByCustomerNo(customerNo);
        String mySign = MD5Utils.getMD5Sign(param, customer.getApiKey(), 1);
        if (!mySign.equals(sign)) {
            throw new BusinessException("签名错误");
        }
        Passageway passageway = passagewayService.selectByCustomerNoAndPayCode(customer.getCode(), param.get("payCode"));
        if (passageway == null) {
            throw new BusinessException("通道未授权，请联系平台");
        }
        param.put("passagewayName", passageway.getName());

        /**------------验证通过-------------*/
        Map data = new HashMap();
        if ("nongye".contains(passageway.getMethodName())) {
            double integral = Integer.parseInt(amount);
            String pageUrl = passageway.getApiUrl() + "&pay_type=" + passageway.getPayType()
                    + "&integral=" + integral * 0.01
                    + "&back_url=" + notify_url + "/api/notify/nongye"
                    + "&back_order_sn=" + param.get("outTradeNo");
            //保存订单记录
            tradeService.save(param);
            data.put("pageUrl", pageUrl);
        }
        else if ("wxNative".contains(passageway.getMethodName())) {
            SysCompany company = companyService.selectByCode(customer.getCode().split("-")[0]);
            Merchant merchant = merchantService.selectByReceiveTimeOrder(1, company.getCode());
            WxpayService wxpayService = new WxpayService(company, merchant.getSubMchId(), null);
            JSONObject result = wxpayService.sendNative(outTradeNo, amount, notify_url + "/api/notify/wxNative");
            //保存订单记录
            param.put("merchantId", merchant.getId().toString());
            param.put("merchantName", merchant.getName());
            tradeService.save(param);
            data.put("pageUrl", result.getString("codeUrl"));
        }
        //大发支付
        else if ("dafa".contains(passageway.getMethodName())) {
            SortedMap<String, String> postData = new TreeMap();
            postData.put("shop_phone", passageway.getAccount());
            postData.put("order_number", outTradeNo);
            double payment = Integer.parseInt(amount);
            postData.put("payment", payment * 0.01 + "");
            postData.put("passageway_code", passageway.getPayType());
            postData.put("sign", MD5Utils.getSha256Sign(postData, passageway.getPassword(), 1));
            postData.put("name", "商品");
            postData.put("notify_url", notify_url + "/api/notify/dafa");
            String str = HttpClientUtils.get(passageway.getApiUrl(), postData, "UTF-8");
            log.debug("大发支付建订单返回:" + str);
            JSONObject obj = JSON.parseObject(str);
            if (obj.getInteger("code") == 1) {
                String pageUrl = obj.getString("data");
                //保存订单记录
                tradeService.save(param);
                data.put("pageUrl", pageUrl);
            }else {
                throw new BusinessException(obj.getString("msg"));
            }
        }
        return Result.success(data);
    }

}
